<template>
  <div :class="{ 'dark-mode': isDarkMode }">
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">物业管理系统</a>
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNav"
          aria-controls="navbarNav"
          aria-expanded="false"
          aria-label="切换导航"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
              <a class="nav-link" href="#announcements">公告与通知</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#ownerInfo">我的物业信息</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#activities">物业动态</a>
            </li>
          </ul>

          <!-- 右侧功能区 -->
          <ul class="navbar-nav ms-auto mb-2 mb-lg-0 align-items-center">
            <li v-if="ownerInfo.roomCount > 0" class="nav-item me-3">
              <span class="badge bg-secondary">
                房间数: <strong>{{ ownerInfo.roomCount }}</strong>
              </span>
            </li>


            <li class="nav-item me-3">
              <el-switch
                v-model="isDarkMode"
                active-text="🌙"
                inactive-text="🌞"
                @change="toggleDarkMode"
              />
            </li>

            <li class="nav-item">
              <button class="btn btn-danger btn-sm" @click="logout">
                退出
              </button>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- 页面标题区 -->
    <div class="py-5 mb-4 bg-light rounded">
      <h2 class="text-center text-primary fw-bold">欢迎来到物业管理系统</h2>
      <p class="text-center text-secondary">
        在这里您可以查看最新公告、了解您的物业信息、浏览物业动态和进行查询
      </p>
    </div>

    <div class="container">
      <!-- 公告与通知 -->
      <section id="announcements" class="card shadow-sm mb-4">
        <div class="card-header bg-info d-flex align-items-center">
          <i class="bi bi-megaphone-fill me-2"></i>
          <h5 class="mb-0">公告与通知</h5>
        </div>
        <div class="card-body">
          <div v-if="announcements && announcements.length > 0">
            <div
              v-for="(item, index) in announcements"
              :key="index"
              class="announcement-item mb-3"
            >
              <strong class="text-danger">[公告]</strong>
              <span class="fw-bold">{{ item.title }}</span>
              <p>{{ item.content }}</p>
              <hr />
            </div>
          </div>
          <p v-else class="text-muted">暂无公告</p>
        </div>
      </section>

      <!-- 业主个人物业信息 -->
      <section id="ownerInfo" class="card shadow-sm mb-4">
        <div class="card-header bg-success d-flex align-items-center">
          <i class="bi bi-building me-2"></i>
          <h5 class="mb-0">我的物业信息</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div v-if="ownerInfo.name" class="col-md-6 mb-2">
              <strong>业主姓名：</strong> {{ ownerInfo.name }}
            </div>
            <div v-if="ownerInfo.phone" class="col-md-6 mb-2">
              <strong>联系电话：</strong> {{ ownerInfo.phone }}
            </div>
            <div v-if="ownerInfo.owner_id" class="col-md-6 mb-2">
              <strong>业主ID：</strong> {{ ownerInfo.owner_id }}
            </div>
            <div v-if="ownerInfo.unit_number" class="col-md-6 mb-2">
              <strong>单元号：</strong> {{ ownerInfo.unit_number }}
            </div>
            <div v-if="ownerInfo.floor" class="col-md-6 mb-2">
              <strong>楼层：</strong> {{ ownerInfo.floor }}
            </div>
            <div v-if="ownerInfo.roomCount > 0" class="col-md-6 mb-2">
              <strong>房间数量：</strong> {{ ownerInfo.roomCount }}
            </div>
          </div>
        </div>
      </section>

      <!-- 物业动态/活动 -->
      <section id="activities" class="card shadow-sm mb-4">
        <div class="card-header bg-warning d-flex align-items-center">
          <i class="bi bi-newspaper me-2"></i>
          <h5 class="mb-0">物业动态</h5>
        </div>
        <div class="card-body">
          <div v-if="activities && activities.length > 0">
            <ul class="list-group list-group-flush">
              <li
                v-for="(activity, index) in activities"
                :key="index"
                class="list-group-item d-flex justify-content-between align-items-center"
              >
                <div>
                  <strong>{{ activity.title }}</strong>
                  <p class="mb-0">{{ activity.description }}</p>
                </div>
              </li>
            </ul>
          </div>
          <p v-else class="text-muted">暂无动态</p>
        </div>
      </section>
    </div>

    <!-- 查询单元信息模态框 -->
    <el-dialog v-model:visible="showUnitModal" title="单元详情" width="40%">
      <div v-if="unitDetails">
        <p><strong>单元号：</strong> {{ unitDetails.unit_number }}</p>
        <p><strong>建筑物：</strong> {{ unitDetails.building_name }}</p>
        <p><strong>楼层：</strong> {{ unitDetails.floor }}</p>
        <p><strong>房间数量：</strong> {{ unitDetails.room_count }}</p>
      </div>
      <p v-else>未找到单元信息</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUnitModal = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 页脚 -->
    <footer class="footer bg-light text-center py-3 mt-4">
      <p class="mb-0 text-secondary">物业管理系统 &copy; 2023</p>
      <p class="mb-0 text-secondary">如有问题请联系物业管理处</p>
    </footer>
  </div>
</template>

<script>
import axios from "axios";
import {
  ElSwitch,
  ElDialog,
  ElButton,
} from "element-plus";

export default {
  components: {
    ElSwitch,
    ElDialog,
    ElButton,
  },
  data() {
    return {
      announcements: [],
      activities: [],
      query: "",
      queryResult: null,
      isDarkMode: false,
      unitDetails: null,
      showUnitModal: false,
      selectedActivity: null,
      showActivityModal: false,
      token: "", // 用于存储 JWT Token
      ownerInfo: {
        name: "",
        phone: "",
        owner_id: "",
        unit_number: "",
        floor: "",
        roomCount: null,
      },
    };
  },
  mounted() {
    // 获取 Token（从 localStorage 或其他存储中）
    this.token = localStorage.getItem("token");
    if (this.token) {
      this.fetchAnnouncements();
      this.fetchActivities();
      this.fetchOwnerInfo();
      // 获取主题模式
      const darkMode = localStorage.getItem("isDarkMode") === "true";
      this.isDarkMode = darkMode;
    }
  },
  methods: {
    // 切换深色模式
    toggleDarkMode(isDark) {
      localStorage.setItem("isDarkMode", isDark);
    },
    // 获取公告信息
    async fetchAnnouncements() {
      try {
        const response = await axios.get(
          "http://localhost:3008/announcements",
          {
            headers: { Authorization: `Bearer ${this.token}` },
          }
        );
        if (response.data && response.data.data) {
          this.announcements = response.data.data;
        }
      } catch (error) {
        console.error("获取公告失败:", error);
      }
    },
    // 获取动态活动
    async fetchActivities() {
      try {
        const response = await axios.get(
          "http://localhost:3008/activities",
          {
            headers: { Authorization: `Bearer ${this.token}` },
          }
        );
        if (response.data && response.data.data) {
          this.activities = response.data.data;
        }
      } catch (error) {
        console.error("获取活动失败:", error);
      }
    },
    // 获取业主信息
    async fetchOwnerInfo() {
      try {
        const response = await axios.get("http://localhost:3008/users/me", {
          headers: { Authorization: `Bearer ${this.token}` },
        });
        if (response.data && response.data.data) {
          const ownerData = response.data.data;
          this.ownerInfo = {
            name: ownerData.name || "",
            phone: ownerData.phone || "",
            owner_id: ownerData.username || "",
            unit_number: ownerData.unit_number || "",
            floor: ownerData.floor || "",
            roomCount: ownerData.roomCount !== undefined ? ownerData.roomCount : null,
          };
        }
      } catch (error) {
        console.error("获取业主信息失败:", error);
      }
    },
    // 查询单元信息
    async searchUnits() {
      if (!this.query.trim()) {
        this.$message({
          message: "请输入单元号进行查询",
          type: "warning",
        });
        return;
      }
      try {
        const response = await axios.get(
          `http://localhost:3008/unitsList/${this.query}`,
          {
            headers: { Authorization: `Bearer ${this.token}` },
          }
        );
        if (response.data && response.data.data) {
          this.unitDetails = response.data.data;
        } else {
          this.unitDetails = null;
        }
      } catch (error) {
        this.unitDetails = null;
        console.error("查询单元失败:", error);
      } finally {
        this.showUnitModal = true;
      }
    },
    // 查看活动详情
    viewDetails(activity) {
      this.selectedActivity = activity;
      this.showActivityModal = true;
    },
    // 退出登录
    logout() {
      localStorage.removeItem("token");
      this.$router.push("/login");
    },
  },
};
</script>

<style scoped>
.dark-mode {
  background-color: #121212;
  color: white;
}

.navbar {
  margin-bottom: 20px;
}

.card {
  margin-bottom: 20px;
}

footer {
  background-color: #f8f9fa;
  padding: 10px 0;
}

footer p {
  font-size: 14px;
}

.announcement-item {
  border-left: 5px solid #007bff;
  padding-left: 15px;
}
</style>
